/**
 * 触发事件
 * @author xujie
 * @since 2018/10/18
 * @modifier zhangyao 2021/04/24
 */
layui.define(['index', 'form', 'table', 'laypage','zmnSelect', 'layedit',  'laydate'], function (exports) {

    let $ = layui.$;
    let form = layui.form;
    let layer = layui.layer;
    let table = layui.table;
    let laypage = layui.laypage;
    let layedit = layui.layedit;
    let zmnSelect = layui.zmnSelect;
    let laydate = layui.laydate;

    table.init('zmn-table', {
        toolbar: "#zmn-table-tool",
        page: true,
        defaultToolbar: json.showExportExcel ? ['exports'] : [], done: function () {
            $("div[lay-event='LAYTABLE_EXPORT']").attr('lay-event', 'CUSTOM_EXPORT');
        },
        limit: json.pageSize,
        height: 'full-149'
    });

    laypage.render(layui.$.extend({limits:[10, 20, 30, 40, 50,100]},zmnPage.laypageOptions(json)));

    /**
     * 自定义子级搜索框
     * @param selectId
     * @param options
     * 附加参数：
     * {
     *     remote: {
     *         events: {
     *             extendParams: function(){
     *                  return {
     *                      value: null //必填
     *                  }
     *             }
     *         }
     *     }
     * }
     * @return {*}
     */
    let customChildrenSearch = (selectId, options) => {
        let newOptions = zmnSelect.mergeOptions(selectId, options, {
            propMap: {  //选项参数映射配置
                name: "text",   //显示值
                value: "value"  //选中值
            },
            remote: {
                enable: false
            }
        })
        return zmnSelect.searchBox(selectId, newOptions);
    }
    let objectIdentitySelectValue = json.vo.expand ? json.vo.expand.objectIdentity : "";
    /**
     * 初始化对象身份下拉框
     */
    let objectIdentity = xmSelect.render({
        el: '#objectIdentity',
        size: 'mini',
        name: 'expand.objectIdentity',
        autoRow: false,
        radio: true,
        clickClose: true,
        filterable: false,
        disabled: false,
        data: json.objectIdentityList,
        model: {
            label: {
                type: 'block',
                block: {
                    //最大显示数量, 0:不限制
                    showCount: 0,
                    //是否显示删除图标
                    showIcon: false,
                }
            }
        },
        prop: {
            name: 'text',
            selected: 'status'
        },
        on: function (data) {
            let values = data.arr;
            if (values.length == 0) {
                $("#realNameDiv").hide();
                $("#objectIdsDiv").show();
                form.render();
                json.vo.objectSearchValue = null;
                json.vo.objectIdList = [];
                customChildrenSearch("objectIds", {
                    remote: {
                        enable: false
                    }
                });
                return;
            }
            let objectIdentity = values[0].value;
            if (objectIdentitySelectValue != objectIdentity) {
                json.vo.objectSearchValue = null;
                json.vo.objectIdList = [];
                customChildrenSearch("objectIds", {
                    tips: "-请选择-",
                    name: 'objectIds',
                    searchedValue: "",
                    selectedValues: []
                });
            }
            objectIdentitySelectValue = objectIdentity;
            initObjectSelectAndInput(objectIdentity);
            customChildrenSearch("objectIds", {
                remote: {
                    enable: true,
                    url: "/brs/record/search/object",
                    events: {
                        params: function (searchValue, limitPermit) {
                            return {objectIdentity: objectIdentity, keyword: searchValue};
                        }
                    }
                }
            });
            //获取指定下拉框的xmSelect对象，并调用xmSelect原生API
            /*zmnSelect.getXmSelect('objectIds').update({
                data: json.objectIdentityList
            })*/
        }
    });
    initObjectSelect();

    /**
     * 初始化对象搜索下拉框
     */
    function initObjectSelect () {
        let enable = json.vo.objectIdentity != null && json.vo.objectIdentity != "";
        customChildrenSearch("objectIds", {
            tips: "-请选择-",
            name: 'objectIds',
            searchedValue: json.vo.objectSearchValue,
            selectedValues: json.vo.objectIdList, //已选中值（用于回显)
            remote: {
                url: "/brs/record/search/object",
                enable: enable,
                events: {
                    extendParams: function () {
                        return {
                            value: json.vo.objectIdentity
                        }
                    },
                    params: function (searchValue, limitPermit) {
                        return {objectIdentity: json.vo.objectIdentity, keyword: json.vo.objectSearchValue};
                    }
                },
            },
            events: {
                changed: function (values) {
                }
            }
        })
    }
    initObjectSelectAndInput(json.vo.objectIdentity);
    function initObjectSelectAndInput (val) {
        if (val == 4) {
            $("#realNameDiv").show();
            $("#objectIdsDiv").hide();
            json.vo.objectIds = [];
            initObjectSelect();
        } else {
            $("#realName").val("");
            $("#realNameDiv").hide();
            $("#objectIdsDiv").show();
        }
        form.render();
    }

    /*zmnSelect.searchStaff('objectIds', {
        searchedValue: json.vo.objectSearchValue,
        selectedValues: json.vo.objectIds,
        remote: {
            limitPermit: json.vo.limitPermit,
            events: {
                extendParams: function () {
                    return {
                        status: 2,
                    }
                }
            }
        },
        events: {
            changed: function (values) {

            }
        }
    });*/
    $('#objectIds .xm-search-input').on('input propertychange', function () {
        let objectSearchValue = $('#objectIds .xm-search-input').val();
        json.vo.objectSearchValue = objectSearchValue;
        $("#objectSearchValue").val(objectSearchValue);
    });

    /*zmnSelect.searchEngineer('engineerIds', {
        searchedValue: json.vo.engineerSearchValue,
        selectedValues: json.vo.engineerIds,
        remote: {
            limitPermit: json.vo.limitPermit,
            events: {
                extendParams: function () {
                    return {
                        plat: 10,
                    }
                }
            }
        },
        events: {
            changed: function (values) {

            }
        }
    });*/

    $('#engineerIds .xm-search-input').on('input propertychange', function () {
        let engineerSearchValue = $('#engineerIds .xm-search-input').val();
        json.vo.engineerSearchValue = engineerSearchValue;
        $("#engineerSearchValue").val(engineerSearchValue);
    });

    let eventType = xmSelect.render({
        el: '#eventType',
        size: 'mini',
        name: 'eventType',
        autoRow: false,
        radio: true,
        clickClose: true,
        filterable: false,
        disabled: false,
        data: json.typeList,
        model: {
            label: {
                type: 'block',
                block: {
                    //最大显示数量, 0:不限制
                    showCount: 0,
                    //是否显示删除图标
                    showIcon: false,
                }
            }
        },
        prop: {
            name: 'text',
            selected: 'status'
        },
    });

    // 渲染日期范围选择器
    laydate.render({
        elem: '#timeSearch',
        range: true,
        min: json.dayLimit,
        max: 0,
        format: 'yyyy/MM/dd',
        trigger: 'click'
    });

    table.on("toolbar(zmn-table)", function (obj) {

        if (obj.event === 'CUSTOM_EXPORT') {
            $("#query-export").click();
        }
    })

    // 重写查询方法
    form.on('submit(zmn-form-submit)', function (data) {

        // 重置为第一页
        $("#pageIndex").val(1);
        $("#zmn-form").submit();
    });

    form.on('submit(query-export)', function (data) {
        if (json.vo.exportLimit === null || json.vo.exportLimit === 0) {
            layer.msg("您没有配置导出数量，无法导出", {"icon": 2});
            return false
        }
        let index = layer.load(1, {
            shade: [0.5, '#DBDBDB'] //0.1透明度的白色背景
        });
        let dataUrl = urlEncode(data.field);
        let fileName = "安全监控.xlsx";
        zmnBrs.download("/brs/record/exportRecordExcel.action?" + dataUrl.slice(1), fileName, function () {
            layer.close(index);
        });
        return false;
    });

    //对外暴露的接口
    exports('record_list', {});
});



let zmnBrs = {
    download(url, fileName = new Date().toISOString(), done = () => {
    }) {
        fetch(url, {
            credentials: 'include'
        }).then(res => res.blob().then(blob => {
            let a = document.createElement('a');
            let url = window.URL.createObjectURL(blob);
            let filename = fileName;
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
            done(blob);
        }))
    }
}

/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 *
 * return URL参数字符串
 */
let urlEncode = function (param, key, encode) {

    if(param == null) {
        return '';
    }
    let paramStr = '';
    let t = typeof (param);
    if (t === 'string' || t === 'number' || t === 'boolean') {
        paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
    } else {
        for (let i in param) {
            let k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
            paramStr += urlEncode(param[i], k, encode);
        }
    }
    return paramStr;
};

